/*
* @Date: 2021/1/1
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import Layer from 'ochart/core/Layer';
import Rectangle from 'ochart/base/Rectangle';

export default class extends Layer {
  constructor(canvas, style, data = []) {
    super(canvas, style);
    this.data = data;
    this.redColor = style.redColor || '#D43932';
    this.greenColor = style.greenColor || '#46A834';
    this.count = style.count;
    this.onMaked = style.onMaked;
  }

  make() {
    this.childs.splice(0, this.childs.length);
    if (this.data.length === 0) {
      return;
    }
    const xStep = this.width / this.count;
    let max = Number.MIN_VALUE;
    for (let i = 0; i < this.data.length; i++) {
      if (this.data[i].volume > max) {
        max = this.data[i].volume;
      }
    }
    const yStep = this.height * 0.8 / max;
    const yMax = max / 0.8;
    const rect1 = new Rectangle(this.canvas, {
      width: xStep,
      height: this.data[0].volume * yStep,
      color: '#999999',
    });
    rect1.setPosition(this.position.x, this.position.y + rect1.height / 2);
    this.addChild(rect1);
    for (let i = 1; i < this.data.length; i++) {
      const rect = new Rectangle(this.canvas, {
        width: xStep,
        height: this.data[i].volume * yStep,
        color: (this.data[i].close > this.data[i - 1].close ? this.redColor : this.greenColor),
      });
      rect.setPosition(this.position.x + i * xStep, this.position.y + rect.height / 2);
      this.addChild(rect);
    }
    this.onMaked && this.onMaked({
      xStep,
      yStep,
      max: yMax,
    });
  }
}
